package org.springframework.ioc.beanfactory.test.common;

import junit.framework.TestCase;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.parsing.AliasDefinition;
import org.springframework.beans.factory.parsing.ComponentDefinition;
import org.springframework.beans.factory.parsing.DefaultsDefinition;
import org.springframework.beans.factory.parsing.ImportDefinition;
import org.springframework.beans.factory.parsing.ReaderEventListener;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

public class BeanFactoryBaseCase extends TestCase {

	public static BeanFactory beanFactory;
	
	public static boolean instanceNow;
	
	public BeanFactoryBaseCase(boolean now){
		instanceNow = now;
	}
	
	@Override
    protected void setUp() throws Exception {
        super.setUp();
        if(beanFactory == null){
        	ClassPathResource resource = new ClassPathResource("org/springframework/ioc/beanfactory/beaninit.xml");
        	if(instanceNow){
        		buildInstanceClazz(resource);
    		}else{
    			buildDefinedClass(resource);
    		}
        }
    }
	
	public void buildDefinedClass(Resource resource){
		beanFactory = new XmlBeanFactory(resource);
	}
	
	public void buildInstanceClazz(Resource resource){
		beanFactory = new DefaultListableBeanFactory();
    	XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader((DefaultListableBeanFactory)beanFactory);
    	//reader.setEventListener(new BeanInstanceEvent());
    	reader.loadBeanDefinitions(resource);
	}
	
	class BeanInstanceEvent implements ReaderEventListener {

		@Override
		public void defaultsRegistered(DefaultsDefinition defaultsDefinition) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void componentRegistered(ComponentDefinition defined) {
			System.out.println(defined.getName()+": do instance");
			beanFactory.getBean(defined.getName());
		}

		@Override
		public void aliasRegistered(AliasDefinition aliasDefinition) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void importProcessed(ImportDefinition importDefinition) {
			// TODO Auto-generated method stub
			
		}
		
	}
}
